//
//  UEAfter_Time.swift
//  Extensions
//
//  Created by gupengling on 2021/6/5.
//  Copyright © 2021 gupengling. All rights reserved.
//

import UIKit

//MARK: - 延迟执行的全局的方法
/// 延迟执行的方法
///
/// - Parameters:
///   - seconds: 秒数
///   - afterToDo: 需要延迟执行的闭包(就是需要延迟执行的那件事)
public func DispatchAfter(_ seconds: Int, _ afterToDo: @escaping ()->()) {
    let deadlineTime = DispatchTime.now() + .seconds(seconds)
    DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
        afterToDo()
    }
}

public func OperationMain(_ toDo: @escaping ()->()) {
    OperationQueue.main.addOperation {
        toDo()
    }
}

public func DispatchMain(_ toDo: @escaping ()->()) {
    DispatchQueue.main.async {
        toDo()
    }
}


/*
 TimeConsuming {
    doSomeThing()
 }
 */
public func TimeConsuming(_ f: () -> ()) {
    let start = CACurrentMediaTime()
    f()
    let end = CACurrentMediaTime()
    print("测量时间：\(end - start)")
}

public func DispathAsyncMain(_ asyncQueue: @escaping ()->(), mainQueue: @escaping ()->()) {
    DispatchQueue.global(qos: .default).async {
        asyncQueue()
        DispatchMain(mainQueue)
    }
}
/**锁
 static func get(key: String) ->  Any? {
     return synchronized(self, { () -> Any? in
         if let obj = getObj(by: key) {
             return obj
         }
         debugPrint("Not Register module of \(key)")
         return nil
     })
 }
 **/
public func synchronized<T>(_ lock: AnyObject, _ body: () throws -> T) rethrows -> T {
    objc_sync_enter(lock)
    defer { objc_sync_exit(lock) }
    return try body()
}
